﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using Sustainalytics.Utils;

namespace Sustainalytics.LongRunningTaskManager.Interface
{
    /// <summary>
    /// Long Running Task status.
    /// </summary>
    public class LongRunningTaskStatus : IEqualityComparer<LongRunningTaskStatus>
    {
        private ConcurrentBag<LongRunningTaskError> _errors;

        /// <summary>
        /// Task progress.
        /// </summary>
        public float? Progress { get; set; }        

        /// <summary>
        /// Errors encountered during the execution of a Long Running Task.
        /// </summary>
        public IEnumerable<LongRunningTaskError> Errors
        {
            get
            {
                return _errors.ToList();
            }
            set
            {
                _errors = new ConcurrentBag<LongRunningTaskError>();

                value.ToList().ForEach(err => _errors.Add(err));
            }
        }

        /// <summary>
        /// Details associated to current status.
        /// </summary>
        public string Details { get; set; }

        public string PortfolioName { get; set; }

        /// <summary>
        /// Ctor.
        /// </summary>
        public LongRunningTaskStatus()
        {
            this.Errors = new ConcurrentBag<LongRunningTaskError>();
        }


        /// <summary>
        /// Add error.
        /// </summary>
        /// <param name="err"> Error. </param>
        public void AddError(LongRunningTaskError err)
        {
            _errors.Add(err);
        }


        public bool Equals(LongRunningTaskStatus x, LongRunningTaskStatus y)
        {
            if (x == null && y == null)
                return true;

            if (x == null || y == null)
                return false;

            return x.Progress.NearlyEq(y.Progress)
                && x.Errors.SequenceEqual(y.Errors, new LongRunningTaskError())
                && ((x.Details == null && y.Details == null) || x.Details == y.Details);
        }

        public int GetHashCode(LongRunningTaskStatus obj)
        {
            return 0;
        }
    }
}
